<?php
/**
 * DES加密
 * @author JohnnyDen <413819942@qq.com>
 * @package package_name api\crypt
 * @copyright 2018年11月5日
 */
namespace api\crypt;

class Des{
    
    public static function encrypt($data, $key) {
        $size = mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_ECB);
        $key = substr(md5($key),0,$size);
        $str = self::pkcs5Pad ($data, $size);
        return base64_encode(mcrypt_ecb(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT));
    }
    
    public static function decrypt($data, $key) {
        $size = mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_ECB);
        $key = substr(md5($key),0,$size);
        $str = mcrypt_ecb(MCRYPT_DES, $key, base64_decode($data), MCRYPT_DECRYPT);
        $str = self::pkcs5Unpad($str);
        return $str;
    }
    
    private static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen ($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    
    private static function pkcs5Unpad($text) {
        $pad = ord ($text[strlen ($text) - 1]);
        if ($pad > strlen($text)) {
            return false;
        }
        if (strspn ($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }
        return substr ($text, 0, - 1 * $pad);
    }
    
}